{% extends 'base_generic.html' %}

{% block content %}
<div class="container py-4">
  <div class="card">
    <div class="card-body">
      <h3 class="card-title">AI 图书馆助手对话</h3>
      <div id="chat-box" style="height:300px;overflow-y:auto;background:#f8f9fa;padding:1em;border-radius:8px;margin-bottom:1em;"></div>
      <div class="input-group">
        <input type="text" id="user-input" class="form-control" placeholder="请输入你的问题...">
        <button id="send-btn" class="btn btn-primary">发送</button>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

const chatBox = document.getElementById('chat-box');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');

function appendMessage(sender, text) {
  const msg = document.createElement('div');
  msg.innerHTML = `<b>${sender}：</b> ${text}`;
  msg.style.marginBottom = '0.5em';
  chatBox.appendChild(msg);
  chatBox.scrollTop = chatBox.scrollHeight;
}

sendBtn.onclick = function() {
  const text = userInput.value.trim();
  if (!text) return;
  appendMessage('你', text);
  userInput.value = '';
  fetch('{% url "ai-chat" %}', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrftoken,
      'X-Requested-With': 'XMLHttpRequest',
    },
    body: JSON.stringify({message: text})
  })
  .then(res => res.json())
  .then(data => {
    appendMessage('AI', data.reply);
  });
};
userInput.addEventListener('keydown', function(e) {
  if (e.key === 'Enter') sendBtn.onclick();
});
</script>
{% endblock %} 